use std::fs;
use clap::{command};
pub use clap::Parser;

/// Welcome to use grep config parser
/// # Examples
/// ```
/// use lgrep::arg_parser::*;
/// let config = Config::parse();
/// println!("query: {}, filepath: {:?}", config.query, config.filepath);
/// ```
#[derive(Parser)]
#[command(version, author, about, long_about)]
pub struct Config {
    /// Specify your query String
    pub query: String,

    /// Specify your file path
    #[arg(long, value_parser=parse_filepath)]
    pub filepath: Option<String>,

    /// Case insensitive search.  
    /// set environment variable method:  
    /// 1. win[set CASE_INSENSITIVE=1]
    /// 2. linux[export CASE_INSENSITIVE=1]
    #[arg(short, long, env="CASE_INSENSITIVE", default_value_t=false, value_parser=parse_env)]
    pub case_insensitive: bool,
}

fn parse_env(env_var: &str) -> Result<bool, String> {
    if env_var.is_empty() || env_var == "0" || env_var == "false" {
        Ok(false)
    }else {
        Ok(true)
    }
}

fn parse_filepath(filepath: &str) -> Result<String, String> {
    match fs::exists(filepath) {
        Ok(is_exist) => {
            if is_exist {
                return Ok(filepath.to_string());
            } else {
                return Err("filepath not exist".to_string());
            }
        },
        Err(e) => {
            return Err(e.to_string());
        }
    }
}
